
import React from "react";
import * as THREE from 'three';
import { useAnimate } from "tools/hooks/useAnimate";
import { RectAreaLightHelper } from "three/examples/jsm/helpers/RectAreaLightHelper";
import Controller from "../Controller";

type LightHelper = THREE.SpotLightHelper | THREE.DirectionalLightHelper | THREE.PointLightHelper | RectAreaLightHelper

/** 聚光灯辅助 */
export default function useLightHelper(controller: Controller) {

    /** 选中原件的UUID */
    const selectedElementUuid = controller.useMemo(s => s.selectedElementUuid, []);

    /** 原件字典 */
    const elementMap = controller.useMemo(s => s.elementMap, []);

    /** 选中的原件 */
    const selectedElement = React.useMemo(() => selectedElementUuid && elementMap.get(selectedElementUuid), [elementMap, selectedElementUuid])

    const scene = controller.useMemo(s => s.scene, []);

    const [lightHelper, setLightHelper] = React.useState<LightHelper>()

    React.useEffect(() => {
        if (!scene) return;

        if (!selectedElement) return;

        // 创建灯光辅助对象
        try {
            const helper = createHelper(selectedElement.object3D);
            setLightHelper(helper);
            scene.add(helper);

            return () => {
                scene.remove(helper);
            }
        } catch (error) {
        }
    }, [scene, selectedElement])

    useAnimate(React.useCallback(() => {
        if (lightHelper instanceof RectAreaLightHelper) {

        } else {
            lightHelper && lightHelper.update()
        }
    }, [lightHelper]))
}


/** 创建灯光辅助对象 */
function createHelper(object3D: any): LightHelper {
    if (object3D instanceof THREE.SpotLight) {
        return new THREE.SpotLightHelper(object3D);
    } else if (object3D instanceof THREE.DirectionalLight) {
        return new THREE.DirectionalLightHelper(object3D, 10)
    } else if (object3D instanceof THREE.PointLight) {
        return new THREE.PointLightHelper(object3D, 1)
    } else if (object3D instanceof THREE.RectAreaLight) {
        return new RectAreaLightHelper(object3D)
    }
    throw new Error("不是灯光对象");
}